#!/usr/bin/env bash

FUNKWHALE=""
INJSON=""
OUTFILE=playlist.m3u
TOKEN=""
while getopts "f:i:o:t:" arg; do
	case $arg in
		f)
			FUNKWHALE=${OPTARG}
			;;
		i)
			INJSON=${OPTARG}
			;;
		o)
			OUTFILE=${OPTARG}
			;;
		t)
			TOKEN=${OPTARG}
			;;
	esac
done
shift $((OPTIND-1))

if [ -z "${INJSON}" ]; then
    echo No infile given
	exit 1
fi

if [ -z "${TOKEN}" ]; then
    echo No token given
	exit 1
fi

if [ ! -f "${INJSON}.tracks.json" ]; then
    echo "Track JSON not found!"
fi

if [ "$(host ${FUNKWHALE}|grep "not found"|wc -l)" -lt 0 ]; then
	echo Instance ${FUNKWHALE} has no DNS entry
	exit 1
fi

if [ "$(curl -s -X 'GET' https://${FUNKWHALE}/api/v1/instance/nodeinfo/2.0/ -H 'accept: application/json' |jq -r '.software.name')" != "funkwhale" ]; then
	echo Instance ${FUNKWHALE} seems not to be a funkwhale instance
	exit 1
fi

nexturl="https://${FUNKWHALE}/api/v1/uploads/"

m3u_name="$(cat "${INJSON}.pl.json"|jq -r '.name'|tr ' ' '_').m3u"
echo $m3u_name

echo "#EXTM3U" > "${m3u_name}"

for i in $(cat "${INJSON}.tracks.json" |jq -r '.results[].track.uploads[].uuid'); do 
	IFS=',' read title path <<< $(curl -s -X 'GET' ${nexturl}$i'/' -H 'accept: application/json' -H "Authorization: Bearer ${TOKEN}"|jq -r '[.track.title,.source]|@csv'|tr -d '"')
	echo "#EXTINF:-1,${title}" >> "${m3u_name}"
	echo $path|rev|cut -d'/' -f1-3|rev >> "${m3u_name}"
done

#for i in $(cat "${INJSON}.tracks.json" |jq -r '.results[].track.uploads[].uuid'); do curl -s -X 'GET' ${nexturl}'/'$i'/' -H 'accept: application/json' -H 'Authorization: Bearer '${TOKEN}; done |jq -r '.source'|rev|cut -d'/' -f1-3|rev
